package com.example.getfromservice.Activity;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.DefaultHttpClient;
import com.example.getfromservice.R;
import com.example.getfromservice.Book.Book;
import com.example.getfromservice.Book.BookDAO;
import com.example.getfromservice.Book.DataHandlerBook;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ThirdActivity extends Activity {

	public List<Book> books_list  ;
	private Bundle extras;
	public Book book = new Book();
	private int cat_id;
	private ListView myListView;
	private ArrayAdapter<Book> adapter;
	private LongRunningGetIO mLongRunningIO = null;
	private LongRunningDelete mLongRunningDelete = null;
	private boolean mDone = true;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private BookDAO bookdatasource;
	private int ID_Object = -1;
	
		
	//*********************************************** ONCREATE ****************************************	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_third);
	
		bookdatasource = new BookDAO(this);
					
		books_list =  new ArrayList<Book>();
		
	    myListView = (ListView)findViewById(R.id.listView1);
	 
	
		extras = getIntent().getExtras();
		cat_id = extras.getInt("CategoryID");
		
		myListView.setOnItemClickListener(new OnItemClickListener() {

		public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
					 ID_Object = myItemInt;
				 	   
			    	 final CharSequence[] items = { "Edit", "Delete", "Info"};

			    	 AlertDialog.Builder builder = new AlertDialog.Builder(ThirdActivity.this);
			    	 builder.setTitle("Pick an action : ");
			    	 builder.setItems(items, new DialogInterface.OnClickListener() {
			 	     
			    public void onClick(DialogInterface dialog, int item) {
			 	
			    	book = books_list.get(ID_Object);
								
			 	    	    switch(item)
			 	    	    {
			 	    	    	
			         	    	
				 	    	      	case 0:
		 	    	    			{
		 	    	    				
	 	    	    					Intent myintent = new  Intent(getApplicationContext(), FourthActivity.class);
	 	    	    						 	    	    					
	 						        	// Info - { category_id ,book_id, action  }
	 						        	// category_id - if new then 0 
	 						        	// action  0 - new ; 1 - update
	 	    	    					
	 	    	    					myintent.putExtra( "Info", new int[]{Integer.parseInt(book.getCategory_id()),book.getID(),1} );
	 									startActivity(myintent);
		 	    	    			}
		         	    	    
		 	    	    			break;
			 	    	    	
				 	    	    	case 1:
				 	    	    			{
				 	    	    				
				 	    	    				books_list.remove(book);
	        	    	    					
	        	    	    					boolean needToCreate = false;
	        	    	    		  			if (mLongRunningDelete == null) {
	        	    	    		  			      needToCreate=true;
	        	    	    		  			} else {
	        	    	    		  				if (mLongRunningDelete.isDone()) {
	        	    	    		  					needToCreate=true;
	        	    	    		
	        	    	    		  					mLongRunningDelete = null;
	        	    	    		  				}
	        	    	    		  			}
	        	    	    		  			if (needToCreate) {
	        	    	    		  				mLongRunningDelete = new LongRunningDelete();
	        	    	    		  				mLongRunningDelete.execute(cat_id+"",book.getID()+"");
	        	    	    		  			}
				 	    	    	
						        	 	    	   
				 	    	    		  			
				 	    	    			}
				         	    	    
				 	    	    		break;
			 	    	    	
					 	    	    	case 2:
					 	    	    		{
					 	    	    			
					 	    	    			Intent myintent = new  Intent(getApplicationContext(), FifthActivity.class);
			 	    	    								 	    	    					
			 						        	// Info - { category_id, book_id , action }
			 						        	// category_id - if new then 0 
			 						        	// action  0 - new ; 1 - update
			 									myintent.putExtra( "Info", new int[]{Integer.parseInt(book.getCategory_id()),book.getID(),1} );
			 									startActivity(myintent);
					 	    	    		}
					     	    	    		
					 	    	    	break;
			 	    	    		
			 	    	    }
			 	       }
			 	   });
			 	   
			 	   AlertDialog alert = builder.create();
			 	   alert.show();
			 	   
			      
				
			}
		});
		
	}

	
	//*********************************************** MENU ****************************************
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_third, menu);
        return true;
    }
	


    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
 
        switch (item.getItemId())
        {
	        case R.id.menu_addbook: 
						        {
				
	 	    	    					Intent myintent = new  Intent(getApplicationContext(), FourthActivity.class);
	 	    	    					int last;
	 	    	    					
	 						        	// Info - { category_id ,book_id, action , last_book_id }
	 						        	// category_id - if new then 0 
	 						        	// action  0 - new ; 1 - update
		 	    	    					if( books_list.size() > 0)
		 	    	    						{
		 	    	    							Book tmp = books_list.get(books_list.size()-1);
		 	    	    						
		 	    	    							last = tmp.getID();
		 	    	    						}
		 	    	    					else
			 	    	    					{
			 	    	    						last = 0;
			 	    	    					}
	 	    	    					
	 	    	    					myintent.putExtra( "Info", new int[]{cat_id,book.getID(),0,last} );
	 									startActivity(myintent);
 								}
	        return true;
        }
        
        return false;
    }

  //*********************************************** ONRESUME ****************************************
	
	 @Override
	    protected void onResume() {
	      
	      super.onResume();
	      bookdatasource.open();
	      
		  boolean needToCreate = false;
			if (mLongRunningIO == null) {
			      needToCreate=true;
			} else {
				if (mLongRunningIO.isDone()) {
					needToCreate=true;

					mLongRunningIO = null;
				}
			}
			if (needToCreate) {
				mLongRunningIO = new LongRunningGetIO();
				mLongRunningIO.execute();
			}
	    }

	    @Override
	    protected void onPause() {
	     
	     super.onPause();
	     bookdatasource.close();
	   
	    }
	
	  //*********************************************** ISONLINE ****************************************
	    
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
       
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
           
        	return true;
        }
        
        return false;
    }
    
  //*********************************************** GETDATA ****************************************
	
	private class LongRunningGetIO extends AsyncTask<Void, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(Void... params) {

			try
	        {
				if( isOnline())
		      		{
				
						DataHandlerBook xmlparser = new DataHandlerBook();
		    	  
						books_list = xmlparser.getAllBooks(cat_id+"");
		    	 
			  	  
		      		}
		      else if( !isOnline() )
		      		{
		    	  
		    	  		books_list = bookdatasource.getAllBooks(cat_id+"");
		    	  
		      		}
	              
	        }
	        catch(Exception pce) 
	        	{ 
	        		Log.e("LongRunningGetIO", "PCE "+pce.getMessage()); 
	        	}
			
			return 1;
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {
 
				  adapter = new ArrayAdapter<Book>(ThirdActivity.this,android.R.layout.simple_list_item_1, books_list);
			      myListView = (ListView)findViewById(R.id.listView1);
			  	  myListView.setAdapter(adapter);
				
				   
			}
	
		}

	}
	
	//*********************************************** DELETE ****************************************
	
    private class LongRunningDelete extends AsyncTask<String, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(String... params) {
		
			try{
					if( !isOnline() )
						{
								book.setChanges(3);
		
							
								bookdatasource.updateBookinDB(book);
						}
					else if( isOnline() )
						{
						
								Log.i("Delete",params[0]+"/"+params[1]);
				
					    	    HttpClient httpclient = new DefaultHttpClient();
					    	    HttpDelete httpdelete = new HttpDelete("http://10.0.2.2:8020/categoryservice/category/"+params[0]+"/"+params[1]);
					    	    
					    	    HttpResponse response = httpclient.execute(httpdelete);  
				
					    	    Log.i("Respones",response.toString());
				    	    	
				        }
			
			}catch(Exception pce) 
			        	{ 
			        	
			        		Log.e("LongRunningDelete", "PCE "+pce.getMessage()); 
			        	
			        	}
				
			
			return 1;
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {
				
				adapter.notifyDataSetChanged(); 
				
			     		
			}
	
		}

	}
   

}